import os
import tkinter as tk
import subprocess
import threading
import re
import time
from tkinter import font
def remove_ansi_escape_sequences(text):
    """移除 ANSI 转义序列"""
    ansi_escape = re.compile(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9,A-Z]{1,2})?(;[0-9,A-Z]{3})?)?[m|K|A|B|C|D]')
    return ansi_escape.sub('', text)
def extract_device_device(device_info):
    """从设备信息中提取设备模式"""
    match = re.search(r'\bMaskrom\b', device_info)
    return match.group(0) if match else "未检测到设备"

def fetch_device_name():
    """定期获取设备名称"""
    while True:
        try:
            process = subprocess.Popen("./rkdeveloptool ld", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
            output = process.communicate()[0]
            device_name = extract_device_device(output)
            update_device_name(device_name)
        except Exception as e:
            update_device_name(f"错误: {e}")
        time.sleep(3)  # 每隔 5 秒更新一次

def run_commands():
    commands = [
        ("ls -l rkdeveloptool", "x"),
        ("./rkdeveloptool ld", None),
        ("echo 'start'", None),
        ("echo 'device list:'", None),
        ("./rkdeveloptool ld", None),
        ("echo '---'", None),
        ("echo 'burner loader...'", None),
        ("./rkdeveloptool db rk3308_bs_loader_uart0_m0_emmc_port_support_sd_20220516.bin", None),
        ("echo 'burner img...'", None),
        ("./rkdeveloptool wl 0 *.img", None),
        ("echo 'burner done'", None),
        ("echo 'reset device'", None),
        ("./rkdeveloptool rd", None)
    ]

    output_text.delete(1.0, tk.END)  # 清空输出框
    burn_status.set("烧录中...")  # 更新烧录状态

    for command, expected_output in commands:
        try:
            if "cd" in command:
                directory = command.split()[1]
                os.chdir(directory)
                update_output(f"当前目录切换到: {directory}\n")
            else:
                process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
                command_displayed = False
                last_line = ""  # 保存上一行的内容
                for line in iter(process.stdout.readline, ""):
                    clean_line = remove_ansi_escape_sequences(line)
                    if not command_displayed:
                        update_output(f"命令: {command}\n")
                        command_displayed = True

                    # 检查是否是进度条行
                    if "Write LBA from file" in clean_line:
                        # 提取进度百分比
                        match = re.search(r'\((\d+)%\)', clean_line)
                        if match:
                            percent = match.group(1)
                            # 如果上一次有相同的行，只更新数字部分
                            if "Write LBA from file" in last_line:
                                last_percent = re.search(r'\((\d+)%\)', last_line)
                                if last_percent:
                                    last_percent = last_percent.group(1)
                                    if percent != last_percent:
                                        update_progress(last_line, percent)
                            else:
                                update_output(clean_line)
                            last_line = clean_line
                    elif clean_line.strip() != last_line.strip() and clean_line.strip():
                        update_output(clean_line)
                        last_line = clean_line

                process.stdout.close()
                process.wait()
                if process.returncode != 0:
                    update_output(f"命令执行失败，返回码: {process.returncode}\n")
                    burn_status.set("烧录失败")
                    return
            update_output("-" * 32 + "\n")
        except subprocess.CalledProcessError as e:
            update_output(f"命令: {command}\n")
            update_output(f"错误:\n{e.stderr}\n")
            update_output("-" * 32 + "\n")
            burn_status.set("烧录失败")
            return
        except FileNotFoundError:
            update_output(f"错误: 目录 {directory} 不存在\n")
            update_output("-" * 32 + "\n")
            burn_status.set("烧录失败")
            return

    burn_status.set("烧录成功")  # 更新烧录状态

def update_output(text):
    """更新文本框的内容"""
    output_text.insert(tk.END, text)
    output_text.see(tk.END)

def update_progress(last_line, new_percent):
    """更新进度百分比"""
    progress.set(f"{new_percent}%")  # 更新进度条
    start = output_text.search(last_line, "1.0", tk.END)
    if start:
        start = output_text.index(start)
        end = output_text.index(f"{start}+{len(last_line)}c")
        output_text.delete(start, end)
        new_line = re.sub(r'\(\d+%\)', f"({new_percent}%)", last_line)
        output_text.insert(start, new_line)
        output_text.see(tk.END)

def update_device_name(name):
    """更新设备名称"""
    device_name.set(name)

def run_commands_thread():
    """在新线程中运行命令"""
    threading.Thread(target=run_commands).start()

# 定义一个函数来创建标签
def create_label(root, text, variable, font=None):
    frame = tk.Frame(root)
    frame.pack(anchor="w", pady=2)
    tk.Label(frame, text=text, font=font).pack(side="left")
    tk.Label(frame, textvariable=variable, font=font).pack(side="left")

# 创建主窗口
root = tk.Tk()
root.title("命令执行器")

# 设备名称
device_name = tk.StringVar(value="未检测到设备")
label_font = font.Font(family="Arial", size=10)  # family 是字体名称，size 是字体大小
create_label(root, "设备名称: ", device_name, label_font)

# 烧录进度
progress = tk.StringVar(value="0%")
create_label(root, "烧录进度: ", progress)

# 烧录状态
burn_status = tk.StringVar(value="未开始")
create_label(root, "烧录状态: ", burn_status)

# 创建按钮
run_button = tk.Button(root, text="开始烧录系统", command=run_commands_thread)
run_button.pack(pady=10)

# 创建文本框用于显示输出
output_text = tk.Text(root, height=20, width=80)
output_text.pack(pady=10)

# 启动设备名称更新线程
threading.Thread(target=fetch_device_name, daemon=True).start()

# 启动主循环
root.mainloop()